package com.sky.config;


import com.sky.properties.BitifulProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3Configuration;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;


import java.net.URI;

/**
 * @author majun
 * @package com.sky.config
 * @date 2025/6/21 02:36
 */
@Slf4j
@Configuration
public class BitifulS3Config {

    @Bean
    public S3Client s3Client(BitifulProperties props) {

        log.info("开始初始化S3Client......");

        try {
            S3Client client = S3Client.builder()
                    .region(Region.of(props.getRegion()))
                    .endpointOverride(URI.create(props.getEndpoint()))
                    .credentialsProvider(StaticCredentialsProvider.create(
                            AwsBasicCredentials.create(props.getAccessKey(), props.getSecretKey())
                    ))
                    .serviceConfiguration(S3Configuration.builder()
                            .pathStyleAccessEnabled(true)
                            .build())
                    .build();

            log.info("S3Client,初始化成功");
            return client;
        } catch (Exception e) {
            log.error("S3Client 初始化失败: {}", e.getMessage(), e);
            throw new RuntimeException("S3Client 初始化失败", e);
        }
    }

    @Bean
    public S3Presigner s3Presigner(BitifulProperties props) {
        try {
            S3Presigner presigner = S3Presigner.builder()
                    .region(Region.of(props.getRegion()))
                    .endpointOverride(URI.create(props.getEndpoint()))
                    .credentialsProvider(StaticCredentialsProvider.create(
                            AwsBasicCredentials.create(props.getAccessKey(), props.getSecretKey())
                    ))
                    .build();

            log.info("S3Presigner 初始化成功");
            return presigner;
        } catch (Exception e) {
            log.error("S3Presigner 初始化失败: {}", e.getMessage(), e);
            throw new RuntimeException("S3Presigner 初始化失败", e);
        }
    }

}
